import store from "../../store";

require('./jmessage-sdk-web.2.6.0.min');

function getWebSocket(signature,username,password) {
  let JIM = new JMessage({debug: false});

  JIM.init(signature).onSuccess(function (data) {
    // console.log(data,'连接成功');
    onLogin();
  }).onFail(function (data) {
    // console.log(data,'连接失败');
  });

  function onLogin() {
    JIM.login({
      'username': username,
      'password': password
    }).onSuccess(function (data) {
      // console.log(data);
      console.log('登陆成功')
      onReceive();
    }).onFail(function (data) {
      //同上
      console.log(data,'登陆失败')
    });
  }

  function onReceive() {
    // console.log('进入事件监听');
    //事件监听
    JIM.onEventNotification(function (data) {
      // console.log(data,'事件监听');
    });

    //接收新信息
    JIM.onMsgReceive(function (data) {
      // console.log(data,'接受新信息');
      if (data.messages[0].content.msg_body.text == 'miniOrderNotice'){ //小程序订单/呼叫
        sessionStorage.setItem('webSocketTime',data.messages[0].content.create_time)
        store.state.webSocketTime = sessionStorage.getItem('webSocketTime')
        sessionStorage.setItem('webSocketText',data.messages[0].content.msg_body.text)
        store.state.webSocketText = sessionStorage.getItem('webSocketText')
        sessionStorage.setItem('newCallNum',data.messages[0].content.msg_body.extras.call_count)
        sessionStorage.setItem('newOrderNum',data.messages[0].content.msg_body.extras.mini_order_count)
        // console.log(sessionStorage.getItem('newOrderNum'),'极光推送收到的小程序订单')
      }else if (data.messages[0].content.msg_body.text == 'flushHotelBaseData'){ //酒店基础信息(协议客户、协议方案、酒店吧商品)变更
        sessionStorage.setItem('webSocketTime',data.messages[0].content.create_time)
        store.state.webSocketTime = sessionStorage.getItem('webSocketTime')
        sessionStorage.setItem('webSocketText',data.messages[0].content.msg_body.text)
        store.state.webSocketText = sessionStorage.getItem('webSocketText')
      }
    });

    //离线消息同步监听
    JIM.onSyncConversation(function (data) {
      /*暂不处理离线消息*/
      // console.log(data,'离线消息同步监听')
      // if (data.messages[0].content.msg_body.text == 'miniOrderNotice'){ //小程序订单
      //   store.state.webSocketText = data[0].msgs[0].content.msg_body.text
      //   store.state.webSocketTime = data[0].msgs[0].content.create_time
      //   store.state.webSocketNum = data.length
      // }
    });
  }

  function addSingleReceiptReport(username, msgids) {
    JIM.addSingleReceiptReport({
      'username': username,
      'msg_ids': msgids
    }).onSuccess(function (data, msg_ids) {
      // console.log('已读回执成功');
      // console.log(data);
      // console.log(msg_ids);
      // data.code 返回码
      // data.appkey 目标 appkey
      // data.username 目标 username
      // msg_ids 消息数组
    }).onFail(function (data) {
      console.log(data);
    })
  }
}

export default {
  getWebSocket
}
